Welcome to Django!

1.6 响应HTML页面

#视图函数,必需有一个参数

from django.contrib import admin

from django.urls import path

from django.shortcuts import HttpResponse

from django.conf import settings # 导入是为了读入根文件settings.BASE_DIR。不然会出错

import os

# shortcuts 捷径:绍特卡特

# ‌conf配置文件‌在Python中通常用于存储和读取配置信息, 其格式类似于INI文件,由sections和items组成,sections用于区分不同的配置块, items是sections下的键值对。Python提供了configparser模块来方便地读取和修改conf配置文件。



def hello(request):

filepath=os.path.join(settings.BASE_DIR, "shn","hello_world.html")

with open (filepath, "r" ) as f:

content=f.read()

return HttpResponse(content)

1、总路由urls(在文件shn=>shn里面,参考载图)

urlpatterns = [

path( 'admin/' , admin.site.urls),

path( 'hello/' , include("hello.urls")),

]

2、在第一个shn下面再设置一个文件hello,里面增加分路由urls:

from django.urls import path

from. import views

urlpatterns = [

]path('hello', views.hello),

]

运行后地址是:http://127.0.0.1:8000/hello



以下是hello_world.html文件

<!DOCTYPE html >

<html >

<head >

<title >Hello World < / title >

<style >

body {

background-color: #f2f2f2;

font-family: Arial, sans-serif;

text-align: center;

margin-top: 150px;

}

h1 {

color: #333333;

font-size: 36px;

margin-bottom: 20px;

}

p {

color: #666666;

font-size: 18px;

margin-bottom: 40px;

}

.button {

background-color: #4CAF50;

color: white;

padding: 10px 20px;

text-align: center;

text-decoration: none;

display: inline-block;

font-size: 16px;

border-radius: 4px;

transition-duration: 0.4s;

cursor: pointer;

}

.button:hover {

background-color: #45a049;

}

< /title >

< /head >

< body >

< h1 > Hello World </h1 >

< p> Welcome to my beautiful webpage! < /p>

< a href ="#" class ="button" >Click Me </a >

</body >

</html >